package com.yjz.study.http

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.yjz.common.restful.Convert
import com.yjz.common.restful.HttpBaseResponse
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.lang.reflect.Type

/**
 * 接口相应返回的实体类
 */
class GsonConvert : Convert {
    private var gson: Gson = Gson()

    @Suppress("UNCHECKED_CAST")
    override fun <T> convert(rawData: String, dataType: Type): HttpBaseResponse<T> {
        val response: HttpBaseResponse<T> = HttpBaseResponse()
        try {
            val jsonObject = JSONObject(rawData)
            response.code = jsonObject.optInt("code")
            response.msg = jsonObject.optString("msg")
            val data = jsonObject.opt("data")
            if ((data is JSONObject) or (data is JSONArray)) {
                if (response.code == HttpBaseResponse.SUCCESS) {
                    response.data = gson.fromJson(data?.toString(), dataType)
                } else {
                    response.errorData = gson.fromJson<MutableMap<String, String>>(
                        data?.toString(),
                        object : TypeToken<MutableMap<String, String>>() {}.type
                    )
                }
            } else {
                response.data = data as T?
            }
        } catch (e: JSONException) {
            e.printStackTrace()
            response.code = -1
            response.msg = e.message
        }
        response.rawData = rawData
        return response
    }

}